package com.mobilezu.mobile.common.service.impl;

import java.util.List;

import javax.persistence.EntityExistsException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataIntegrityViolationException;

import com.mobilezu.mobile.common.dao.SystemUserDaoable;
import com.mobilezu.mobile.common.model.SystemUser;
import com.mobilezu.mobile.common.service.SystemUserServiceable;
import com.mobilezu.mobile.pushserver.service.UserExistsException;
import com.mobilezu.mobile.pushserver.service.UserNotFoundException;


public class SystemUserServiceImpl implements SystemUserServiceable {

	protected final Log log = LogFactory.getLog(getClass());

	private SystemUserDaoable systemUserDao;

	public void setSystemUserDao(SystemUserDaoable systemUserDao) {
		this.systemUserDao = systemUserDao;
	}

	public SystemUser getSystemUser(String SystemUserId) {
		return systemUserDao.getSystemUser(new Long(SystemUserId));
	}

	public List<SystemUser> getSystemUsers() {
		return systemUserDao.getSystemUsers();
	}

	public SystemUser saveSystemUser(SystemUser SystemUser) throws UserExistsException {
		try {
			return systemUserDao.saveSystemUser(SystemUser);
		} catch (DataIntegrityViolationException e) {
			e.printStackTrace();
			log.warn(e.getMessage());
			throw new UserExistsException("User '" + SystemUser.getUsername()
					+ "' already exists!");
		} catch (EntityExistsException e) { // needed for JPA
			e.printStackTrace();
			log.warn(e.getMessage());
			throw new UserExistsException("User '" + SystemUser.getUsername()
					+ "' already exists!");
		}
	}

	@SuppressWarnings("finally")
	public SystemUser getSystemUserByUsername(String SystemUsername) {
		SystemUser returnUser = null;
		try {
			returnUser = (SystemUser) systemUserDao
					.getSystemUserByUsername(SystemUsername);
		} catch (UserNotFoundException e) {
			log.warn("Username '" + SystemUsername + "' not found");
		} finally {
			return returnUser;
		}
	}

	public void removeSystemUser(Long SystemUserId) {
		log.debug("removing SystemUser: " + SystemUserId);
		systemUserDao.removeSystemUser(SystemUserId);
	}

}
